﻿using System;
using System.Linq;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db.System;
using HengTong.Model._Admin;
using Microsoft.EntityFrameworkCore;


namespace HengTong.ViewModel.Wechat.SysWechatUserVms
{
    public partial class SysWechatUserBatchVm : BaseBatchVM<SysWechatUser, SysWechatUserBatchEdit>
    {
        public SysWechatUserBatchVm()
        {
            ListVM = new SysWechatUserListVm();
            LinkedVM = new SysWechatUserBatchEdit();
        }

        public async Task<int> BatchUnbindAsync()
        {
            if (Ids == null || !Ids.Any())
            {
                return 0;
            }

            var count = await DC.Set<SysWechatUser>()
                .Where(x => Ids.Contains(x.ID.ToString()))
                .ExecuteUpdateAsync(x =>
                    x.SetProperty(y => y.UserId, (Guid?)null));
            await DC.SaveChangesAsync();
            return count;
        }

        /// <summary>
        /// 删除所有未绑定的微信用户
        /// </summary>
        /// <returns>删除的用户数量</returns>
        public async Task<int> DeleteUnboundUsersAsync()
        {
            // 获取admin用户的ID
            var adminUserId = await DC.Set<FrameworkUser>()
                .Where(x => x.ITCode == "admin")
                .Select(x => x.ID)
                .FirstOrDefaultAsync();

            // 删除所有未绑定的微信用户，但排除与admin用户绑定的
            var count = await DC.Set<SysWechatUser>()
                .Where(x => x.UserId == null || x.UserId == adminUserId)
                .ExecuteDeleteAsync();

            await DC.SaveChangesAsync();
            return count;
        }
    }

    /// <summary>
    /// Class to define batch edit fields
    /// </summary>
    public class SysWechatUserBatchEdit : BaseVM
    {
        protected override void InitVM()
        {
        }
    }
}